package frame.base;

import frame.util.shiro.UserRealm;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BaseWeb {

    protected void checkFormData(BindingResult bd) throws IllegalArgumentException{
        if (bd.hasErrors()) {
            StringBuilder sb = new StringBuilder("参数错误：");
            bd.getFieldErrors().stream().forEach(error -> {
                sb.append(error.getDefaultMessage()).append(";");
            });
            throw new IllegalArgumentException(sb.toString());
        }
    }
    protected Integer strId2Integer(String arg) {
        try {
            return Integer.parseInt(arg);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("ID必须为Integer");
        }
    }
    protected List<Integer> strId2Integer(String[] args) {
        List<Integer> list = new ArrayList<>();
        if (args == null || args.length == 0) {
            return list;
        }
        for (int i = 0; i < args.length; i++) {
            try {
                list.add( Integer.parseInt(args[i]) );
            } catch (NumberFormatException e) {
                //忽略id错误的数据
            }
        }
        return list;
    }


    /**
     * 权限异常
     * <br>用于shiro的权限注解 @RequiresRoles
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public void authorizationExceptionHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        // TODO 增加日志 username 越权访问 url
        response.sendRedirect("/403");
        Thread.sleep(200);
        String uri = request.getRequestURI();
        System.out.println(UserRealm.getSystemUserLoginUsername() + " 越权访问uri = " + uri);
    }
}
